import React from "react";
import ReactDOM from "react-dom";
// import {
//   HashRouter,
//   BrowserRouter,
//   Routes,
//   Route,
//   Link,
//   Outlet,
//   useNavigate,
//   useLocation,
//   useParams,
// } from "react-router-dom";
import {
  HashRouter,
  BrowserRouter,
  Routes,
  Route,
  Link,
  Outlet,
  useNavigate,
  useLocation,
  useParams,
} from "./my-react-router-dom";

const UserAPI = {
  list() {
    const usersStr = localStorage.getItem("users");
    const users = usersStr ? JSON.parse(usersStr) : [];
    return users;
  },
  add(user) {
    const users = UserAPI.list();
    users.push(user);
    localStorage.setItem("users", JSON.stringify(users));
  },
  find(id) {
    const users = UserAPI.list();
    return users.find((user) => user.id === id);
  },
};

function Home() {
  return <div>Home</div>;
}

function User() {
  return (
    <div>
      <ul>
        <li>
          <Link to="/user/list">用户列表</Link>
        </li>
        <li>
          <Link to="/user/add">添加用户</Link>
        </li>
      </ul>
      <div>
        <Outlet />
      </div>
    </div>
  );
}

function UserList() {
  const [users, setUsers] = React.useState([]);

  React.useEffect(() => {
    const users = UserAPI.list();
    setUsers(users);
  }, []);

  return (
    <ul>
      {users.map((user, index) => (
        <li key={index}>
          <Link to={`/user/detail/${user.id}`} state={user}>
            {user.name}
          </Link>
        </li>
      ))}
    </ul>
  );
}

function UserAdd() {
  const navigate = useNavigate();
  const nameRef = React.useRef();

  const handleSubmit = (event) => {
    event.preventDefault();
    const name = nameRef.current.value;
    UserAPI.add({ id: Date.now() + "", name });
    navigate("/user/list");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={nameRef} />
      <button type="submit">添加</button>
    </form>
  );
}

function UserDetail() {
  const location = useLocation();
  const { id } = useParams();
  const [user, setUser] = React.useState({});

  React.useEffect(() => {
    let user = location.state; // 取路径对象上的状态

    if (!user && id) {
      user = UserAPI.find(id);
    }

    if (user) setUser(user);
  }, []);

  return (
    <div>
      id: {user.id}
      <br />
      name: {user.name}
    </div>
  );
}

const App = () => {
  return (
    <BrowserRouter>
      <ul>
        <Link to="/">Home</Link>
        <Link to="/user/add">Profile</Link>
        <Link to="/user/list">Detail</Link>
      </ul>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/user" element={<User />}>
          <Route path="add" element={<UserAdd />} />
          <Route path="list" element={<UserList />} />
          <Route path="detail/:id" element={<UserDetail />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
